package com.xuecheng.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xuecheng.media.mapper.MediaFilesMapper;
import com.xuecheng.media.mapper.MediaProcessHistoryMapper;
import com.xuecheng.media.mapper.MediaProcessMapper;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.model.po.MediaProcess;
import com.xuecheng.media.model.po.MediaProcessHistory;
import com.xuecheng.media.service.MediaProcessService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author shiminghui
 * @date 2024/8/26 9:05
 * @description: TODO
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MediaProcessServiceImpl implements MediaProcessService {

    private final MediaProcessMapper mediaProcessMapper;

    private final MediaFilesMapper mediaFilesMapper;

    private final MediaProcessHistoryMapper mediaProcessHistoryMapper;

    /**
     * 保存任务信息
     *
     * @param taskId   任务id
     * @param status   状态
     * @param fileId   文件id
     * @param url      文件路径
     * @param errorMsg 错误信息
     */
    @Override
    public void saveProcessFinishStatus(Long taskId, String status, String fileId, String url, String errorMsg) {

        //先查询到任务
        MediaProcess mediaProcess = mediaProcessMapper.selectById(taskId);

        //如果查询结果为空,直接返回
        if (mediaProcess == null) {
            return;
        }

        //如果查询结果不为空
        //判断任务完成情况
        LambdaUpdateWrapper<MediaProcess> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(MediaProcess::getId, mediaProcess.getId());

        if (status.equals("3")) {//失败了

            mediaProcess.setStatus(status);
            mediaProcess.setErrormsg(errorMsg);
            mediaProcess.setFailCount(mediaProcess.getFailCount() + 1);
            mediaProcess.setUrl("");

            int update = mediaProcessMapper.update(mediaProcess, updateWrapper);
            log.error("修改任务状态失败,任务id:{},错误信息:{}", taskId, errorMsg);
            return;
        }

        //成功了
        //修改媒资信息表
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileId);
        if (mediaFiles != null) {
            mediaFiles.setUrl(url);
            int i = mediaFilesMapper.updateById(mediaFiles);
            if (i <= 0) {
                log.error("修改媒资信息表失败,文件参数:{}", mediaFiles);
            }
        }

        //修改任务表
        //处理成功，更新url和状态
        mediaProcess.setUrl(url);
        mediaProcess.setStatus("2");
        mediaProcess.setFinishDate(LocalDateTime.now());
        mediaProcessMapper.updateById(mediaProcess);

        //添加到历史记录
        MediaProcessHistory mediaProcessHistory = new MediaProcessHistory();
        BeanUtils.copyProperties(mediaProcess, mediaProcessHistory);
        mediaProcessHistoryMapper.insert(mediaProcessHistory);
        //删除mediaProcess
        mediaProcessMapper.deleteById(mediaProcess.getId());

    }

    /**
     * 查询要处理的任务队列
     *
     * @param shardTotal 总分片数
     * @param shardIndex 分片索引
     * @param count      每一次执行任务的最大数量
     * @return
     */
    @Override
    public List<MediaProcess> selectListByShardIndex(int shardTotal, int shardIndex, int count) {
        List<MediaProcess> mediaProcesses = mediaProcessMapper.selectListByShardIndex(shardTotal, shardIndex, count);
        return mediaProcesses;
    }

    /**
     * 开启一个任务
     *
     * @param taskId 任务id
     */
    @Override
    public Boolean startTask(Long taskId) {
        int i = mediaProcessMapper.startTask(taskId);
        return i <= 0 ? false : true;
    }
}
